# !flask/bin/python
# -*- coding: utf-8 -*-
from flask import Flask
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from config import Config
from face_recognition.recognition.image_tools import ImageTools
from face_recognition.utils.log_utils import LoggerUtil

db = SQLAlchemy()
app = Flask(__name__, static_url_path='/face_recognition')
app.config.from_object(Config)
db.app = app
db.init_app(app)
socketio = SocketIO(app)
# Flask-SQLAlchemy must be initialized before Flask-Marshmallow.
# 使用Schema支持持久化对象的序列化
ma = Marshmallow(app)

from face_recognition.models import user_info, face_data, face_index

try:
	db.create_all(app=app)
except Exception as err:
	if err.__class__.__name__.__eq__("OperationalError"):
		LoggerUtil.info("貌似数据库无法连接成功，请检查数据库或者网络是否正常！")
	raise err

LoggerUtil.info("正在准备人脸识别模型，这个过程可能需要一些时间，请耐心等待......")
from face_recognition.recognition.model_manage import ModelManager
from face_recognition.recognition.feature_manage import FeatureManager

# 启动之后，需要从数据库加载所有的人脸特征，并且进行模型训练
# 先看看是否有已经pickle好的模型，如果没有，则需要进行训练
feature_manager = FeatureManager()
model_manager = ModelManager()

# 先尝试从文件中读取，如果文件无法恢复，再尝试从数据库中查询特征
LoggerUtil.info("系统尝试加载人脸特征训练数据和相应的标签集合......")
feature_manager.load_features_and_labels()
LoggerUtil.info("系统尝试重新训练人脸识别模型......")
model_manager.train(feature_manager.train_faces, feature_manager.train_face_labels)

from face_recognition.views import face_collect, login, index, page_redirect, user_info, face_detect
from face_recognition.websocket import face_websocket
from face_recognition.service.task_model_check import check_for_update

LoggerUtil.info("尝试启动定时任务：定期检测是否有新的用户的人脸信息需要训练......")


# 定时任务之一：检测是否有人脸更新
def run_check_for_update():
	with db.app.app_context():
		check_for_update()
